import React, { useEffect, useState } from 'react'
import Home from '../../views/sandbox/home/home'
import Nopermission from '../../views/sandbox/nopermission/Nopermission'
import RightList from '../../views/sandbox/right-manage/rightList'
import RoleList from '../../views/sandbox/right-manage/roleList'
import UserList from '../../views/sandbox/user-manage/userList'
import NewsAdd from '../../views/sandbox/news-manage/newsAdd'
import NewsDraft from '../../views/sandbox/news-manage/newsDraft'
import NewsCategory from '../../views/sandbox/news-manage/newsCategory'
import Audit from '../../views/sandbox/audit-manage/audit'
import AuditList from '../../views/sandbox/audit-manage/auditList'
import Unpublished from '../../views/sandbox/publish-manage/unpublished'
import Published from '../../views/sandbox/publish-manage/published'
import Sunset from '../../views/sandbox/publish-manage/sunset'
import NewsPreview from '../../views/sandbox/news-manage/newsPreview'

import axios from 'axios'
import { Routes, Route, Navigate } from 'react-router-dom'
export default function NewsRouter() {
  //获取全部路由
  const [BackRouteList, setBackRouteList] = useState([])
  useEffect(() => {
    axios.get('/rights').then((res1) => {
      axios.get('/children').then((res2) => {
        setBackRouteList([...res1.data, ...res2.data])
      })
    })
  }, [])

  const LocalRouterMap = {
    '/home': <Home></Home>,
    '/user-manage/list': <UserList></UserList>,
    '/right-manage/role/list': <RoleList></RoleList>,
    '/right-manage/right/list': <RightList></RightList>,
    '/news-manage/add': <NewsAdd></NewsAdd>,
    '/news-manage/draft': <NewsDraft></NewsDraft>,
    '/news-manage/category': <NewsCategory></NewsCategory>,
    '/news-manage/preview/:id': <NewsPreview></NewsPreview>,
    '/audit-manage/audit': <Audit></Audit>,
    '/audit-manage/list': <AuditList></AuditList>,
    '/publish-manage/unpublished': <Unpublished></Unpublished>,
    '/publish-manage/published': <Published></Published>,
    '/publish-manage/sunset': <Sunset></Sunset>,
  }
  //根据key获取组件
  const checkRoute = (item) => {
    return LocalRouterMap[item.key] && (item.pagepermisson || item.routepermisson)
  }
  //看看是否真的有权限
  const checkUserPermission = (item) => {
    const rights = JSON.parse(localStorage.getItem('token')).role.rights
    return rights.includes(item.key)
  }

  return (
    <div>
      <Routes>
        {BackRouteList.map((item) => {
          if (checkRoute(item) && checkUserPermission(item)) {
            return (
              <Route path={item.key} element={LocalRouterMap[item.key]}></Route>
            )
          }
          return null
        })}
        <Route
          path="/"
          exact
          element={<Navigate to="/home"></Navigate>}
        ></Route>
        {BackRouteList.length > 0 && (
          <Route path="*" element={<Nopermission />} />
        )}
      </Routes>
    </div>
  )
}
